package com.repair.controller;

import com.repair.entity.User;
import com.repair.service.UserService;
import com.repair.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody User user) {
        userService.register(user);
        return ResponseEntity.ok().build();
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> loginForm) {
        String token = userService.login(loginForm.get("username"), loginForm.get("password"));
        return ResponseEntity.ok(Map.of("token", token));
    }

    @GetMapping("/profile")
    public ResponseEntity<?> getProfile(@RequestHeader("Authorization") String token) {
        try {
            // 移除"Bearer "前缀
            String jwtToken = token.startsWith("Bearer ") ? token.substring(7) : token;
            String username = jwtUtil.extractUsername(jwtToken);
            
            if (username == null || username.isEmpty()) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("无效的token");
            }

            User user = userService.findByUsername(username);
            if (user == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户不存在");
            }

            // 验证token是否有效
            if (!jwtUtil.validateToken(jwtToken, user)) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("token已过期或无效");
            }

            return ResponseEntity.ok(user);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("获取用户信息失败: " + e.getMessage());
        }
    }

    @PutMapping("/profile")
    public ResponseEntity<?> updateProfile(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.parseLong(request.get("id").toString());
            String realName = (String) request.get("realName");
            String phone = (String) request.get("phone");
            String email = (String) request.get("email");
            String address = (String) request.get("address");
            String oldPassword = (String) request.get("oldPassword");
            String newPassword = (String) request.get("newPassword");

            // 更新基本信息
            User user = userService.getById(userId);
            if (user == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("用户不存在");
            }

            user.setRealName(realName);
            user.setPhone(phone);
            user.setEmail(email);
            user.setAddress(address);
            userService.updateById(user);

            // 如果提供了新密码，则更新密码
            if (newPassword != null && !newPassword.isEmpty()) {
                if (oldPassword == null || oldPassword.isEmpty()) {
                    return ResponseEntity.badRequest().body("请输入原密码");
                }
                userService.changePassword(userId, oldPassword, newPassword);
            }

            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("更新失败：" + e.getMessage());
        }
    }

    @PostMapping("/change-password")
    public ResponseEntity<?> changePassword(@RequestBody Map<String, String> passwordForm) {
        userService.changePassword(
                Long.parseLong(passwordForm.get("userId")),
                passwordForm.get("oldPassword"),
                passwordForm.get("newPassword")
        );
        return ResponseEntity.ok().build();
    }

    @GetMapping("/{id}")
    public ResponseEntity<?> getUser(@PathVariable Long id) {
        User user = userService.getById(id);
        return ResponseEntity.ok(user);
    }

    @PutMapping("/{id}/status")
    public ResponseEntity<?> updateUserStatus(
            @PathVariable Long id,
            @RequestBody Map<String, Integer> request) {
        userService.updateUserStatus(id, request.get("status"));
        return ResponseEntity.ok().build();
    }
} 